// 表单问题项选择
export const dictOption = [
  {
    label: '是',
    value: 1,
    // isRight: true, // 是否正确 正确则加分
    optionStatus: 1, // 1 正确 2 错误 3 不适用
  },
  {
    label: '否',
    value: 2,
    // isError: true, // 选择否为错误项
    optionStatus: 2, // 1 正确 2 错误 3 不适用
  },
  {
    label: '不适用',
    value: 3,
    // isInapplicable: true,
    optionStatus: 3, // 1 正确 2 错误 3 不适用
  },
];

/*
 * 转换数据为app需要格式
 * params:表单详情接口返回数据
 * recordId:创建的表单id
 */
export function changeFormToAppData(params, recordId = '') {
  const fields = params.fields?.map((x) => JSON.parse(x));
  const formValue = params.modeuleJsonList
    ? params.modeuleJsonList?.find((x) => x.moduleCode === '0')
    : {};
  // debugger
  const values = formValue.resultJson ? JSON.parse(formValue.resultJson) : {};
  // 表单头部配置信息列表
  const formHeadList = getFormTitleField(fields, values);

  // 表单默认信息模块
  const {
    formName,
    formId,
    deptName,
    deptId,
    score,
    state,
    qualityType,
    qualityResultRate,
    qualityModuleUsers,
    qualityDate,
    nurseNames,
    roundsTime,
  } = params;

  const master = {
    id: recordId,
    qcName: formName,
    wardName: deptName,
    wardCode: deptId,
    evalDate: qualityDate || roundsTime,
    nurseNames,
    score,
    formId,
    state,
    qualityType,
    qualityResultRate,
    qualityModuleUsers,
  };
  // 获取表单模块统计数据
  const { totalScore, userScore, yesSize, noSize, inapplicableSize, allItems, totalNum } =
    countModuleList(fields, values, 1);
  const itemCount = {
    allSize: totalNum,
    yesSize,
    noSize,
    inapplicableSize,
    evalRate: qualityResultRate,
    netTotalScore: userScore,
    deductTotalScore: totalScore - userScore,
    inapplicableTotalScore: 0, // 不适用 一般计算为-1
    useScore: true,
    totalScore,
    qualifiedRate: qualityResultRate,
  };
  // 问题模块
  const itemGroupList = allItems.map((x) => {
    return {
      qcItemTypeName: x.moduleTitle,
      remark: x.moduleRemark,
      allSize: x.moduleAllSize,
      yesSize: x.moduleYesSize,
      noSize: x?.moduleNoSize,
      inapplicableSize: x?.moduleInapplicableSize,
      evalRate: x?.moduleEvalRate,
      moduleCode: x.moduleCode,
      itemList: x?.moduleQuestions,
      moduleFillNum: x.moduleFillNum,
      moduleHasFilled: x.moduleHasFilled,
      moduleRemarkCode: x.moduleRemarkCode,
    };
  });

  return {
    master,
    itemCount,
    itemGroupList,
    formHeadList,
  };
}
// 获取表单头部
export function getFormTitleField(fields, values) {
  const titleFields = [];
  fields
    ?.filter((x) => x?.__config__?.moduleType === 1)
    ?.forEach((item) => {
      if (item && item?.__config__?.children) {
        item.__config__.children.forEach((y) => {
          if (y?.__config__ && y?.__vModel__) {
            titleFields.push({
              label: y?.__config__?.label,
              value: values?.[y.__vModel__] || y?.__config__?.defaultValue,
              __vModel__: y.__vModel__,
              required: !!y?.__config__?.required,
              disabled: !!y?.disabled,
              isStatistical: !!y?.isStatistical,
              tag: y?.__config__?.tag,
            });
          }
        });
      }
    });
  return titleFields;
}

// 处理数据为接口所需数据
export function changeFormToApiData(fields, values, userId) {
  // 问题模块
  const moduleList = [];
  // 获取表单头模块
  fields.forEach((fieldModule) => {
    // 获取头部信息
    const moduleConfig = fieldModule.__config__;

    if (moduleConfig?.moduleType === 1) {
      moduleConfig?.children?.forEach((x) => {
        // 如果是需要统计字段
        if (x?.isStatistical) {
          const statField = {
            detailDtoList: [
              {
                questionValue: values[x.__vModel__],
                reasonId: null,
                valueType: 0,
              },
            ],
            formId: values.formId,
            moduleCode: null,
            operator: userId,
            questionCode: x.__vModel__,
            remark: x?.__config__?.label,
            score: -1,
            totalScore: -1,
          };
          moduleList.push(statField);
        }
      });
    }
    // valueType: 0表头 1原因-问题库 2选项 3子选项
    // 获取问题信息
    if (moduleConfig.moduleType === 2) {
      const moduleCode = moduleConfig.formId;
      const moduleTitleItem = moduleConfig?.children?.find(
        (x) => x?.__config__?.componentName === 'html-div',
      );

      const questionList = [];
      (moduleConfig.children || []).forEach((item) => {
        const itemConfig = item.__config__;
        // const moduleRemark = itemConfig?.children?.find(x => x?.__vModel__?.startsWith('remark'))
        if (itemConfig.moduleType === 3) {
          const questionCode = itemConfig.formId;
          let remarkItem = itemConfig?.children?.find((x) => x?.__vModel__?.startsWith('remark'));

          const curQuest = {
            remark: remarkItem ? values[remarkItem.__vModel__] : '',
            operator: userId,
            detailDtoList: [],
            formId: values.formId,
            moduleCode,
            moduleName: moduleTitleItem?.__config__?.label,
            questionCode,
          };
          itemConfig.children.forEach((op) => {
            if (op?.__vModel__?.startsWith('title')) {
              const questionResult = values[op.__vModel__];
              let score =
                values.questionScoreList?.find((x) => x.questionCode === questionCode)
                  ?.questionUserScore || 0;
              if (values[`operator_${op.__vModel__}`]) {
                curQuest.operator = values[`operator_${op.__vModel__}`]?.userId;
              }

              // 选择不适用的时候设为-1
              const qcItemValue =
                dictOption?.find((x) => x.value === op?.__config__?.defaultValue)?.label || '';
              if (questionResult === '不适用') {
                score = -1;
              }

              curQuest.detailDtoList.push({
                questionValue: qcItemValue,
                reasonId: null,
                valueType: 2,
              });

              curQuest.score = score;
              curQuest.totalScore = op.__config__.score || 0;
            } else if (op?.__vModel__?.startsWith('subItem')) {
              const subSelect = values[op.__vModel__];
              const subList = subSelect?.map((x) => {
                const selectValue = op?.__slot__?.options?.find((y) => y.value === x)?.label || '';
                return {
                  questionValue: selectValue,
                  reasonId: null,
                  valueType: 3,
                };
              });
              subList && curQuest.detailDtoList.push(...subList);
            } else if (op?.__vModel__?.startsWith('reason')) {
              const subSelect = values[op.__vModel__];
              const subList = subSelect?.map((x) => {
                return {
                  questionValue: x.description,
                  reasonId: x.id,
                  valueType: 1,
                };
              });
              subList && curQuest.detailDtoList.push(...subList);
            }
          });
          questionList.push(curQuest);
        }
      });

      moduleList.push(...questionList);
    }
  });
  return moduleList;
}

// 获取表单错题列表
export function getErrorFormItems(fields, values) {
  const result = [];

  for (let i = 0; i < fields?.length; i++) {
    const moduleCode =
      fields[i]?.__config__?.moduleType === 2 ? fields[i]?.__config__?.formId : null;
    if (moduleCode) {
      let hasSelectNo = false;
      const newForm = JSON.parse(JSON.stringify(fields[i]));
      newForm.__config__.children = [];
      // debugger
      fields[i]?.__config__?.children?.forEach((item) => {
        const questionCode = item?.__config__?.moduleType === 3 ? item?.__config__?.formId : null;
        if (questionCode) {
          item?.__config__?.children?.forEach((child) => {
            const noValue = dictOption.find((x) => x.optionStatus === 2);
            const titleFields = child.__vModel__;
            const titleValue = values[titleFields];
            if (titleFields?.startsWith('title') && titleValue === noValue.value) {
              hasSelectNo = true;
              newForm.__config__.children.push(item);
            }
          });
        } else {
          newForm.__config__.children.push(item);
        }
      });
      console.log('newForm', newForm);

      hasSelectNo && result.push(newForm);
    } else {
      result.push(fields[i]);
    }
  }
  return result;
}

// 递归formConfig并根据字段查找 并返回问题层 如：__vModel__
export function findFormModule(fields, filedValue, filed = '__vModel__') {
  const formConfig = fields;
  let result = {};
  const parent = {};
  const grandparent = {};
  function findFormByField(formConfig, parent, grandparent) {
    for (let i = 0; i < formConfig?.length; i++) {
      if (formConfig[i][filed] === filedValue) {
        let moduleCode = null;
        if (grandparent?.__config__?.moduleType === 2) {
          moduleCode = grandparent?.__config__?.formId;
        }
        if (parent?.__config__?.moduleType === 2) {
          moduleCode = parent?.__config__?.formId;
        }
        result = {
          formItem: formConfig[i],
          moduleCode,
          rawParent: parent,
          // grandparent,
        };
        break;
      } else if (formConfig[i]?.__config__?.children?.length) {
        findFormByField(formConfig[i].__config__.children, formConfig[i], parent);
      }
    }
  }

  findFormByField(formConfig, parent, grandparent);
  return result;
}
// 递归表单json 根据表单字段返回当前项
export function getFormItemByField(fields, filedValue, filed) {
  const formConfig = fields || [];
  let result = null;
  function findFormByField(formConfig) {
    for (let i = 0; i < formConfig?.length; i++) {
      if (formConfig[i][filed] === filedValue) {
        result = formConfig[i];
        break;
      } else if (formConfig[i]?.__config__?.children?.length) {
        findFormByField(formConfig[i]?.__config__?.children || []);
      }
    }
  }
  findFormByField(formConfig);
  return result;
}

// 获取表单问题模块标题
export function statFormModules(fields) {
  const allItems = [];
  for (let i = 0; i < fields?.length; i++) {
    const moduleCode =
      fields[i]?.__config__?.moduleType === 2 ? fields[i]?.__config__?.formId : null;
    if (moduleCode) {
      fields[i]?.__config__?.children?.forEach((item) => {
        if (item?.__config__?.componentName === 'html-div') {
          const hasModule = allItems.find((x) => x.moduleCode === fields[i].__config__.moduleCode);
          if (!hasModule && item?.__config__?.label) {
            allItems.push({
              moduleCode,
              moduleTitle: item.__config__.label,
            });
          }
        }
      });
    }
  }
  return allItems;
}

// 统计问题模块所得数据
export function countModuleList(fields, values) {
  // 获取表单分数、合格率、总分、选项数、模块统计列表

  // 问题总分
  let totalScore = 0;
  // 用户得分
  let userScore = 0;
  // 扣分总数
  let deductScore = 0;
  // 选是的总数量
  let yesSize = 0;
  // 选否的总数量
  let noSize = 0;
  // 选不适用的总数量
  let inapplicableSize = 0;
  // 模块列表
  const allItems = [];
  // 每题得分列表
  const questionScoreList = [];
  // 问题总数
  let totalNum = 0;
  // debugger
  for (let i = 0; i < fields.length; i++) {
    const moduleCode =
      fields[i]?.__config__?.moduleType === 2 ? fields[i]?.__config__?.formId : null;
    if (moduleCode) {
      let moduleEvalRate = 0;
      let moduleYesSize = 0;
      let moduleNoSize = 0;
      let moduleInapplicableSize = 0;
      let moduleAllSize = 0;
      let moduleTotalScore = 0;
      let moduleUserScore = 0;
      let moduleTitle = '';
      let moduleFillNum = 0; // 累计填写问题项数
      let moduleHasFilled = false; // 已完成模块数据填写
      const moduleQuestions = [];
      let moduleRemark = '';
      let moduleRemarkCode = null;

      fields[i]?.__config__?.children?.forEach((item) => {
        const questionCode = item?.__config__?.moduleType === 3 ? item?.__config__?.formId : null;
        if (questionCode) {
          moduleAllSize += 1;
          totalNum += 1;
          item?.__config__?.children?.forEach((child, qcItemIndexNo) => {
            if (child?.__vModel__?.startsWith('title')) {
              let {
                score,
                qcItemName,
                deductionScore,
                questionUserScore,
                questionDeductScore,
                titleItem,
                subItem,
                subItemList,
                curSelectOption,
                subSelect,
                questionAllDeductItem,
                remarkItem,
                picListItem,
                reasonItem,
                hadFillItem,
              } = handleQuestionScore(child, item, values);
              // debugger
              // 问题总分
              totalScore += score;
              moduleTotalScore += score;
              moduleUserScore += questionUserScore;
              deductScore += questionDeductScore;
              userScore += questionUserScore;
              const { optionStatus } = curSelectOption || {};
              if (optionStatus) {
                hadFillItem = true;
                moduleFillNum += 1;
                if (optionStatus === 1) {
                  yesSize += 1;

                  moduleYesSize += 1;
                }
                if (optionStatus === 2) {
                  noSize += 1;
                  moduleNoSize += 1;
                }
                if (optionStatus === 3) {
                  inapplicableSize += 1;
                  moduleInapplicableSize += 1;
                }
              }

              questionScoreList.push({ questionCode, questionUserScore, moduleCode });
              const question = {
                qcItemCode: titleItem.__vModel__,
                __vModel__: titleItem.__vModel__,
                qcItemValue: curSelectOption?.label,
                questionResult: values[titleItem.__vModel__],
                subItemResult: subItem?.__vModel__ ? values[subItem.__vModel__] : null,
                remark: remarkItem ? values[remarkItem.__vModel__] : '',
                reasonList: reasonItem ? values[reasonItem.__vModel__] : null,
                picList: picListItem ? values[picListItem.__vModel__] : [],
                qcItemIndexNo,
                questionUserScore,
                qcItemName,
                score,
                questionCode,
                hadFillItem,
                subItemList,
                subItemCode: subItem?.__vModel__,
                picListCode: picListItem?.__vModel__,
                remarkCode: remarkItem?.__vModel__,
                reasonCode: reasonItem?.__vModel__,
                qcItemDeductDesc: titleItem?.__config__?.desc,
                qcItemOptions: titleItem?.__slot__?.options,
              };
              moduleQuestions.push(question);
            }
          });
        } else if (item?.__config__?.componentName === 'html-div') {
          moduleTitle = item.__config__?.label;
        } else if (item?.__vModel__?.startsWith('remark')) {
          moduleRemark = values[item.__vModel__];
          moduleRemarkCode = item.__vModel__;
        }
      });

      moduleEvalRate = moduleYesSize
        ? Number(
            (parseFloat(((moduleYesSize / moduleAllSize) * 10000).toString()) / 100).toFixed(2),
          )
        : 0;

      moduleHasFilled = moduleFillNum === moduleQuestions.length;
      const moduleObj = {
        moduleHasFilled,
        moduleYesSize,
        moduleInapplicableSize,
        moduleEvalRate,
        moduleNoSize,
        moduleAllSize,
        moduleCode,
        moduleTitle,
        moduleFillNum,
        moduleQuestions,
        moduleRemark,
        moduleRemarkCode,
        moduleUserScore,
        moduleTotalScore,
      };
      allItems.push(moduleObj);
    }
  }
  return {
    totalScore,
    userScore,
    yesSize,
    noSize,
    inapplicableSize,
    allItems,
    totalNum,
    deductScore,
    questionScoreList,
  };
}

// 处理每题问题分数情况 得分、扣分、总分、子项分数
export function handleQuestionScore(titleItem, list, values) {
  const qcItemName = titleItem?.__config__?.label;
  const subItem = list?.__config__?.children?.find((x) => x?.__vModel__?.startsWith('subItem'));
  const remarkItem = list?.__config__?.children?.find((x) => x?.__vModel__?.startsWith('remark'));
  const picListItem = list?.__config__?.children?.find((x) => x?.__vModel__?.startsWith('picList'));

  const reasonItem = list?.__config__?.children?.find((x) => x?.__vModel__?.startsWith('reason'));
  const questionAllDeductItem = list?.__config__?.children?.find((x) =>
    x?.__vModel__?.startsWith('questionAllDeduct'),
  );
  const curSelectOption = dictOption.find((x) => x.value === values[titleItem.__vModel__]);

  const subSelect = subItem?.__vModel__ ? values[subItem?.__vModel__] : [];
  // 子选项列表
  const subItemList =
    subItem?.__slot__?.options?.map((x, index) => {
      const checked = subSelect?.some((y) => y === x.value) || false;
      return {
        qcMasterId: x.value,
        subItemName: x.label,
        score: x.score || 0,
        checked,
        index,
        __vModel__: subItem.__vModel__,
      };
    }) || [];
  const score = titleItem?.__config__?.score || 0;
  let hadFillItem = !!curSelectOption;
  // 子项扣分
  let deductionScore =
    subSelect
      ?.map((x) => subItem?.__slot__?.options?.find((y) => y.value === x)?.score || 0)
      .reduce((a, b) => Number(a) + Number(b), 0) || 0;
  let questionUserScore = 0;
  // 问题扣分分数
  let questionDeductScore = 0;

  // 处理选中项和得分
  if (curSelectOption) {
    const { optionStatus } = curSelectOption;
    // 选正确
    // if (optionStatus === 1) {
    //   questionDeductScore = 0
    // }
    // 选错误
    if (optionStatus === 2) {
      // 如果不存在总扣分项
      const {
        __config__: { defaultValue, noDeduct, showLabel2 },
        __vModel__,
      } = questionAllDeductItem || { __config__: {} };
      // let userSubScore = deductionScore ? score - deductionScore : 0
      // 扣分项填写的分数

      let questionAllDeductScore = +defaultValue || 0;
      let userAllDeductScore = 0;
      // 如果存在总扣分项
      if (questionAllDeductItem) {
        userAllDeductScore = handleDiyDeductScore({
          questionAllDeductScore,
          showLabel2,
          noDeduct,
          deductionScore,
          score,
          subItem,
          values,
          __vModel__,
        });
      }
      // 不存在扣分总项则使用子项扣分
      questionDeductScore = questionAllDeductItem
        ? userAllDeductScore
        : subItem
        ? deductionScore
        : score;
    }
    questionUserScore = score - questionDeductScore;
    // 选不适用
    if (optionStatus === 3) {
      questionUserScore = 0;
      questionDeductScore = 0;
    }
    // console.log(qcItemName, questionUserScore, questionDeductScore)
  }

  return {
    score,
    qcItemName,
    deductionScore,
    questionUserScore,
    questionDeductScore,
    titleItem,
    subItem,
    subItemList,
    curSelectOption,
    subSelect,
    questionAllDeductItem,
    remarkItem,
    picListItem,
    reasonItem,
    hadFillItem,
  };
}
// 处理自定义扣分组件
export function handleDiyDeductScore(params) {
  let {
    questionAllDeductScore,
    showLabel2,
    noDeduct,
    deductionScore,
    score,
    subItem,
    values,
    __vModel__,
  } = params;
  let userAllDeductScore;
  // 如果没有自定义扣分

  if (!showLabel2) {
    // 没有子项则扣题目全部分数
    // debugger
    userAllDeductScore = subItem
      ? questionAllDeductScore
      : values[__vModel__] !== undefined
      ? values[__vModel__]
      : score;
    // 如果是自定义扣分且自不扣题目分数
  } else if (showLabel2 && noDeduct) {
    userAllDeductScore = deductionScore ? score - deductionScore : 0;
  } else {
    // 如果是自定义扣分且扣题目分数
    // 如果不存在子项则扣题目全部分数
    userAllDeductScore = subItem
      ? questionAllDeductScore + deductionScore
      : questionAllDeductScore + score;
  }
  return userAllDeductScore;
}
